home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 499 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: mixing enums and integers
  5. Date: Fri, 05 Jan 96 21:40:29 GMT
  6. Organization: none
  7. Message-ID: <820878029snz@genesis.demon.co.uk>
  8. References: <4cij6k$dvb@yrkpa.kias.com>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4cij6k$dvb@yrkpa.kias.com>
  15.            glynis@yrkpa.kias.com "John Flinchbaugh" writes:
  16.  
  17. >the faq states that mixing enums and ints is legal, but poor style.
  18. >
  19. >i'd like to use enums to organize my constants, like this:
  20. >
  21. >        enum DIRECT {UP=72,LEFT=75,RIGHT=77,DOWN=80};
  22. >        int key;
  23. >        getch();        /* dos code to get the second byte of 2-byte */
  24. >        key=getch();    /* key codes from keyboard                   */
  25. >        if (key==UP) printf("up");
  26. >        ...
  27. >
  28. >now this should work, but it's poor style, right?
  29.  
  30. Not in my opinion. You make a clear distinction between an enum type and
  31. the identifiers in an enumerator list. If you write
  32.  
  33.         enum DIRECT direct;
  34.  
  35. then direct has type enum DIRECT which is compatible with an
  36. implementation-defined integer type. It is probably bad style to mix
  37. direct with ints. However the enumerator list identifiers such as UP, LEFT
  38. etc. have type int according to the standard; it is quite reasonable
  39. to assign and compare these to ints. IMHO it is in many cases better
  40. style to define constants with enums like this than to use #defines.
  41. There's an example of enums being used like this in section 9.1 of the FAQ.
  42.  
  43. >would casting it be more proper:
  44. >
  45. >        if ((enum DIRECT) key==up) ...
  46.                                 UP
  47.  
  48. Not IMHO.
  49.  
  50. >also, can you typedef enums?  if so, how?
  51.  
  52. The same way as you typedef anything else (in particular structures and
  53. unions).
  54.  
  55.     typedef enum {UP=72,LEFT=75,RIGHT=77,DOWN=80} DIRECT;
  56.  
  57. or
  58.  
  59.     typedef enum Direct {UP=72,LEFT=75,RIGHT=77,DOWN=80} DIRECT;
  60.  
  61. or
  62.  
  63.     enum Direct {UP=72,LEFT=75,RIGHT=77,DOWN=80};
  64.     typedef enum Direct DIRECT;
  65.  
  66. -- 
  67. -----------------------------------------
  68. Lawrence Kirby | fred@genesis.demon.co.uk
  69. Wilts, England | 70734.126@compuserve.com
  70. -----------------------------------------
  71.